from typing import Dict, Any, Optional
from pathlib import Path


class ConfigGeneratorModule:
    """配置生成模块 - 生成.config文件和头文件"""

    @staticmethod
    def generate_dot_config(config_values: Dict[str, Any], output_path: str) -> bool:
        """
        生成.config文件

        Args:
            config_values: 配置值字典 {config_name: value}
            output_path: 输出文件路径

        Returns:
            是否生成成功
        """
        try:
            with open(output_path, "w", encoding="utf-8") as f:
                # 写入文件头
                f.write("#\n")
                f.write("# Automatically generated by Kconfig GUI Editor\n")
                f.write("#\n\n")

                # 按字母顺序写入配置项
                for config_name, value in sorted(config_values.items()):
                    if value is None:
                        continue

                    line = f"CONFIG_{config_name}="

                    if isinstance(value, bool):
                        line += "y" if value else "n"
                    elif isinstance(value, str):
                        if value.lower() in ["y", "yes", "true", "1"]:
                            line += "y"
                        elif value.lower() in ["n", "no", "false", "0"]:
                            line += "n"
                        else:
                            line += f'"{value}"'
                    elif isinstance(value, (int, float)):
                        line += str(int(value))
                    elif isinstance(value, bytes):
                        line += value.decode("utf-8")
                    else:
                        line += str(value)

                    f.write(line + "\n")

            return True
        except Exception as e:
            print(f"Failed to generate .config file: {e}")
            return False

    @staticmethod
    def generate_header_file(
        config_values: Dict[str, Any],
        output_path: str,
        header_guard: Optional[str] = None,
    ) -> bool:
        """
        生成头文件

        Args:
            config_values: 配置值字典 {config_name: value}
            output_path: 输出文件路径
            header_guard: 头文件保护宏，默认为自动生成

        Returns:
            是否生成成功
        """
        try:
            # 自动生成头文件保护宏
            if not header_guard:
                header_guard = Path(output_path).stem.upper() + "_H"

            with open(output_path, "w", encoding="utf-8") as f:
                # 写入文件头
                f.write("/*\n")
                f.write(" * Automatically generated by Kconfig GUI Editor\n")
                f.write(" */\n\n")

                # 写入头文件保护
                f.write(f"#ifndef {header_guard}\n")
                f.write(f"#define {header_guard}\n\n")

                # 按字母顺序写入配置宏
                for config_name, value in sorted(config_values.items()):
                    if value is None:
                        continue

                    if isinstance(value, bool):
                        if value:
                            f.write(f"#define CONFIG_{config_name} 1\n")
                        else:
                            f.write(f"#undef CONFIG_{config_name}\n")
                    elif isinstance(value, str):
                        if value.lower() in ["y", "yes", "true", "1"]:
                            f.write(f"#define CONFIG_{config_name} 1\n")
                        elif value.lower() in ["n", "no", "false", "0"]:
                            f.write(f"#undef CONFIG_{config_name}\n")
                        else:
                            f.write(f'#define CONFIG_{config_name} "{value}"\n')
                    elif isinstance(value, (int, float)):
                        f.write(f"#define CONFIG_{config_name} {int(value)}\n")
                    else:
                        # 其他类型转换为字符串
                        str_value = str(value)
                        f.write(f'#define CONFIG_{config_name} "{str_value}"\n')

                # 写入结束标记
                f.write(f"\n#endif /* {header_guard} */\n")

            return True
        except Exception as e:
            print(f"Failed to generate header file: {e}")
            return False

    @staticmethod
    def generate_config_files(
        config_values: Dict[str, Any], config_dir: str, header_name: str = "autoconf.h"
    ) -> bool:
        """
        生成完整的配置文件集

        Args:
            config_values: 配置值字典 {config_name: value}
            config_dir: 配置文件目录
            header_name: 头文件名

        Returns:
            是否生成成功
        """
        try:
            config_dir_path = Path(config_dir)
            config_dir_path.mkdir(parents=True, exist_ok=True)

            # 生成.config文件
            dot_config_path = config_dir_path / ".config"
            if not ConfigGeneratorModule.generate_dot_config(
                config_values, str(dot_config_path)
            ):
                return False

            # 生成头文件
            header_path = config_dir_path / header_name
            header_guard = f"{config_dir_path.name.upper()}_{header_name.replace('.', '_').upper()}"
            if not ConfigGeneratorModule.generate_header_file(
                config_values, str(header_path), header_guard
            ):
                return False

            return True
        except Exception as e:
            print(f"Failed to generate config files: {e}")
            return False
